package cn.designpattern.state;

// 抽象状态接口
interface UserState {
    String getName();
    void login(User context);
    void logout(User context);
}

// 具体状态：在线状态
class OnlineState implements UserState {
    private static final OnlineState instance = new OnlineState();

    private OnlineState() {}

    public static OnlineState getInstance() {
        return instance;
    }

    @Override
    public String getName() {
        return "OnlineState";
    }

    @Override
    public void login(User context) {
        System.out.println("User is already online.");
    }

    @Override
    public void logout(User context) {
        System.out.println("User logging out...");
        context.setState(OfflineState.getInstance());
    }

}

// 具体状态：离线状态
class OfflineState implements UserState {
    private static final OfflineState instance = new OfflineState();

    private OfflineState() {}

    public static OfflineState getInstance() {
        return instance;
    }

    @Override
    public String getName() {
        return "OfflineState";
    }

    @Override
    public void login(User context) {
        System.out.println("User logging in...");
        context.setState(OnlineState.getInstance());
    }

    @Override
    public void logout(User context) {
        System.out.println("User is already offline.");
    }

}

// 上下文类：用户
class User {

    private final String username;
    private UserState currentState;

    public User(String username) {
        this.username = username;
        this.currentState = OfflineState.getInstance(); // 初始状态为离线
    }

    public void setState(UserState state) {
        System.out.println("User [" + username + "] changed state "+ currentState.getName() +" to " + state.getName());
        this.currentState = state;
    }

    public void login() {
        currentState.login(this);
    }

    public void logout() {
        currentState.logout(this);
    }

}

// 测试类
public class UserStateExample {
    public static void main(String[] args) {
        User user = new User("Alice");
        // 用户操作流程
        user.login();    // 输出：User logging in...
        user.logout();   // 输出：User logging out...
    }
}

